﻿using UnityEngine;
using System.Collections;
using System;
public class SocketClientManager  {

    private float m_HearTime = 4;//4秒
    private float m_lastTime = 0;
   
    private float m_CurLifeTime = 1*60;//5分钟 几分钟没反应关闭连接
    private float m_lastTime2 = 0;

    private float m_ReConnectTime =2;//2秒

    public static SocketClientManager mInst = null;

    private SocketManager socketManager=null;
    public static SocketClientManager GetInstance()
    {
        if (mInst == null)
        {
            mInst = new SocketClientManager();
           
        }
        return mInst;
    }

    public SocketClientManager()
    {
        //mInst = this;
        m_lastTime = m_HearTime;
        m_lastTime2 = m_CurLifeTime;
        socketManager = SocketManager.GetInstance();
        socketManager.Init(this);
    }

    public void Connect(string dwIP, ushort wPort)
    {
        socketManager.OnOpen(dwIP, wPort);
    }

    public  void Update() { 
        UpdateData();
    }

    protected  void UpdateData()//update调用
    {
        socketManager.run();
        // 链接状态
        DateTime dt = DateTime.Now;
        if (socketManager.GetState() == SocketState.state_connectok)
        {
            m_HearTime -= Time.deltaTime;
            if (m_HearTime <= 0)
            {
                // 心跳包
                ByteBuffer byteBuffer = ByteBuffer.Allocate(0);
                Send(new GameMsg(GameMsgCode.Heart_Req, byteBuffer));
                m_HearTime = m_lastTime;
                //Debug.Log("发送心跳"+ dt);
            }
        }
        else if (socketManager.GetState() == SocketState.state_invalid)
        {
            m_ReConnectTime -= Time.deltaTime;
            if (m_ReConnectTime<=0)
            {
                m_ReConnectTime = 2;
                socketManager.OnReConnect();
                //Debug.Log("重连" + dt);
            }
            
          
        }
        CountDownConnectTime();
    }

    // 客户端给GS发消息
    public void Send(GameMsg gameMsg)
    {
        socketManager.Send(gameMsg);
    }

    public void UnInit()
    {//关闭时调用
        socketManager.Uninit();
    }

    private void CountDownConnectTime()
    {
        m_CurLifeTime -= Time.deltaTime;
        if (m_CurLifeTime <= 0)
        {
            Debug.Log("连接关闭");
            SocketManager.GetInstance().PushEvent(EvtType.netevt_fail);
            m_CurLifeTime = m_lastTime2;
        }
    }

    public void ReSetTime()
    {
        m_CurLifeTime = m_lastTime2;
    }


}
